package com.googlecode.gwtbb.server.intermediate.picture;

import com.googlecode.gwtbb.client.shared.entity.picture.Picture;
import com.googlecode.gwtbb.server.dao.picture.PictureDao;
import com.googlecode.gwtbb.server.dao.picture.ThumbDao;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Abraham Grief
 * @version $Id$
 * @since Dec 8, 2008
 */
public class PictureAssembler {
	private PictureDao pictureDao;
	private ThumbDao thumbDao;

	public PictureDao getPictureDao() {
		return pictureDao;
	}

	public void setPictureDao(PictureDao pictureDao) {
		this.pictureDao = pictureDao;
	}

	public ThumbDao getThumbDao() {
		return thumbDao;
	}

	public void setThumbDao(ThumbDao thumbDao) {
		this.thumbDao = thumbDao;
	}

	@Transactional
	public Picture assemble(Long pictureId) {
		return assemble(pictureDao.select(pictureId));
	}

	@Transactional
	public Picture assemble(Picture picture) {
		return doAssemble(picture);
	}

	@Transactional
	public List<Picture> assemble(List<Picture> pictures) {
		for (Picture picture : pictures)
			doAssemble(picture);
		return pictures;
	}

	@Transactional
	private Picture doAssemble(Picture picture) {
		if (picture != null) {
			Picture.Info pictureInfo = picture.getInfo();
			if (pictureInfo == null) {
				Long pictureId = picture.getId();

				// right now there's no need to select PictureInfo from the db... just create it
				pictureInfo = new Picture.Info();

				picture.setInfo(pictureInfo);
				pictureInfo.setId(pictureId);
				pictureInfo.setThumbs(thumbDao.selectByPictureId(pictureId));
			}
		}
		return picture;
	}
}
